﻿package net.wangit.context;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.wangit.Path;
import net.wangit.framework.config.UploadSettings;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class MultiPartRequest {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.dispatcher.DispatcherServlet.class);
	private static final String PJPEG = "image/pjpeg";
	private static final String JPEG = "image/jpeg";
	private static final String SAVE_DIR = (new StringBuilder(Path
			.getHomePath())).append("/temp").toString();
	public static final String FILE_NAME = "filename";
	public static final String CONTENT_TYPE = "contenttype";
	public static final String FILE_SIZE = "filesize";
	private final Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>();
	private final Map<String, List<String>> params = new HashMap<String, List<String>>();
	private final List<String> errors = new ArrayList<String>();

	public MultiPartRequest() {
	}

	public void parse(HttpServletRequest servletRequest) throws IOException {
		DiskFileItemFactory fac = new DiskFileItemFactory();
		fac.setSizeThreshold(0);
		File multipartSaveDir = new File(SAVE_DIR);
		if (!multipartSaveDir.exists()) {
			multipartSaveDir.mkdir();
		}
		fac.setRepository(multipartSaveDir);
		long maxSize = UploadSettings.getConfig().getMaxSize();
		try {
			ServletFileUpload upload = new ServletFileUpload(fac);
			upload.setSizeMax(maxSize);
			@SuppressWarnings("unchecked")
			List<FileItem> items = upload
					.parseRequest(createRequestContext(servletRequest));
			Iterator<FileItem> iterator = items.iterator();
			while (iterator.hasNext()) {
				FileItem item = iterator.next();
				String fieldName = item.getFieldName();
				if (item.isFormField()) {
					log.debug((new StringBuilder(String.valueOf(fieldName)))
							.append(" : normal form field").toString());
					List<String> values;
					if (params.get(fieldName) != null)
						values = params.get(fieldName);
					else
						values = new ArrayList<String>();
					String charset = servletRequest.getCharacterEncoding();
					if (charset != null)
						values.add(item.getString(charset));
					else
						values.add(item.getString());
					params.put(fieldName, values);
				} else {
					log.debug((new StringBuilder(String.valueOf(fieldName)))
							.append(" : file upload").toString());
					List<FileItem> values;
					if (files.get(fieldName) != null) {
						values = files.get(fieldName);
					} else {
						values = new ArrayList<FileItem>();
						files.put(fieldName, values);
					}
					if (item.getName() == null
							|| item.getName().trim().length() < 1) {
						log.debug((new StringBuilder(
								"No file has been uploaded for the field: "))
								.append(fieldName).toString());
						values.add(null);
					} else {
						values.add(item);
					}
				}
			}

			String fieldName;
			Enumeration<String> fileParameterNames = getFileParameterNames();
			while (fileParameterNames != null
					&& fileParameterNames.hasMoreElements()) {
				fieldName = fileParameterNames.nextElement();
				setFileFieldsValue(params, fieldName);
			}

		} catch (org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e) {
			errors.add((new StringBuilder("上传的文件大小超出最大限制")).append(maxSize)
					.append("字节").toString());
		} catch (FileUploadException e) {
			log.error("Unable to parse request", e);
			errors.add(e.getMessage());
		}
	}

	public Enumeration<String> getFileParameterNames() {
		return Collections.enumeration(files.keySet());
	}

	private void setFileFieldsValue(Map<String, List<String>> params,
			String fieldName) {
		List<FileItem> items = files.get(fieldName);
		if (items != null) {
			List<String> values = new ArrayList<String>(items.size());
			List<String> contentTypes = new ArrayList<String>(items.size());
			List<String> fileNames = new ArrayList<String>(items.size());
			List<String> fileSizes = new ArrayList<String>(items.size());
			Iterator<FileItem> iterator = items.iterator();
			while (iterator.hasNext()) {
				FileItem fileItem = iterator.next();
				if (fileItem == null) {
					values.add(null);
					contentTypes.add(null);
					fileNames.add(null);
					fileSizes.add(null);
				} else {
					File file = ((DiskFileItem) fileItem).getStoreLocation();
					values.add(file.getPath());
					contentTypes.add(formatContentType(fileItem
							.getContentType()));
					fileNames.add(getCanonicalName(fileItem.getName()));
					fileSizes.add(Long.toString(file.length()));
				}
			}

			params.put(fieldName, values);
			params.put((new StringBuilder(String.valueOf(fieldName))).append(
					MultiPartRequest.CONTENT_TYPE).toString(), contentTypes);
			params.put((new StringBuilder(String.valueOf(fieldName))).append(
					MultiPartRequest.FILE_NAME).toString(), fileNames);
			params.put((new StringBuilder(String.valueOf(fieldName))).append(
					MultiPartRequest.FILE_SIZE).toString(), fileSizes);
		}
	}

	public File[] getFile(String fieldName) {
		List<FileItem> items = files.get(fieldName);
		if (items == null)
			return null;
		List<File> fileList = new ArrayList<File>(items.size());
		Iterator<FileItem> iterator = items.iterator();
		while (iterator.hasNext()) {
			FileItem fileItem = iterator.next();
			if (fileItem == null) {
				fileList.add(null);
			} else {
				fileList.add(((DiskFileItem) fileItem).getStoreLocation());
			}
		}

		return fileList.toArray(new File[fileList.size()]);
	}

	public String[] getFilesystemName(String fieldName) {
		List<FileItem> items = files.get(fieldName);
		if (items == null)
			return null;
		List<String> fileNames = new ArrayList<String>(items.size());
		Iterator<FileItem> iterator = items.iterator();
		while (iterator.hasNext()) {
			FileItem fileItem = iterator.next();
			if (fileItem == null) {
				fileNames.add(null);
			} else {
				fileNames.add(((DiskFileItem) fileItem).getStoreLocation()
						.getName());
			}
		}

		return fileNames.toArray(new String[fileNames.size()]);
	}

	public String getParameter(String name) {
		List<String> v = params.get(name);
		if (v != null && v.size() > 0)
			return v.get(0);
		else
			return null;
	}

	public Enumeration<String> getParameterNames() {
		return Collections.enumeration(params.keySet());
	}

	public String[] getParameterValues(String name) {
		List<String> v = params.get(name);
		if (v != null && v.size() > 0)
			return v.toArray(new String[v.size()]);
		else
			return null;
	}

	public List<String> getErrors() {
		return errors;
	}

	private String getCanonicalName(String filename) {
		int forwardSlash = filename.lastIndexOf("/");
		int backwardSlash = filename.lastIndexOf("\\");
		if (forwardSlash != -1 && forwardSlash > backwardSlash)
			filename = filename.substring(forwardSlash + 1, filename.length());
		else if (backwardSlash != -1 && backwardSlash >= forwardSlash)
			filename = filename.substring(backwardSlash + 1, filename.length());
		return filename;
	}

	private String formatContentType(String contentType) {
		if (MultiPartRequest.PJPEG.equals(contentType))
			return MultiPartRequest.JPEG;
		else
			return contentType;
	}

	private RequestContext createRequestContext(final HttpServletRequest req) {
		return new RequestContext() {
			public String getCharacterEncoding() {
				return req.getCharacterEncoding();
			}

			public String getContentType() {
				return req.getContentType();
			}

			public int getContentLength() {
				return req.getContentLength();
			}

			public InputStream getInputStream() throws IOException {
				InputStream in = req.getInputStream();
				if (in == null)
					throw new IOException("Missing content in the request");
				else
					return req.getInputStream();
			}

		};
	}

}
